<template>
  <div 
    ref="chartRef" 
    :style="{ width: width, height: height }"
    class="echart-container"
  ></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  // 图表配置项
  options: {
    type: Object,
    required: true
  },
  // 图表宽度
  width: {
    type: String,
    default: '100%'
  },
  // 图表高度
  height: {
    type: String,
    default: '300px'
  },
  // 主题
  theme: {
    type: String,
    default: ''
  }
})

const chartRef = ref(null)
let chartInstance = null

// 初始化图表
const initChart = () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value, props.theme)
    chartInstance.setOption(props.options)
  }
}

// 监听容器大小变化
const resizeHandler = () => {
  chartInstance?.resize()
}

// 监听配置项变化
watch(
  () => props.options,
  (newValue) => {
    chartInstance?.setOption(newValue)
  },
  { deep: true }
)

// 监听主题变化
watch(
  () => props.theme,
  () => {
    if (chartInstance) {
      const option = chartInstance.getOption()
      chartInstance.dispose()
      initChart()
      chartInstance.setOption(option)
    }
  }
)

onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeHandler)
})

onUnmounted(() => {
  window.removeEventListener('resize', resizeHandler)
  chartInstance?.dispose()
})
</script>

<style scoped>
.echart-container {
  position: relative;
}
</style>
